package cn.example.vip.mall.file.service.impl;

import cn.example.vip.mall.file.config.FastdfsConfig;
import cn.example.vip.mall.file.entity.FileResult;
import cn.example.vip.mall.file.service.FastDFSService;
import cn.example.vip.mall.file.wrapper.FastDFSClientWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Service
public class FastDFSServiceImpl implements FastDFSService {
	
	@Resource
	private FastDFSClientWrapper fastDFSClientWrapper;
	@Resource
	private FastdfsConfig fastdfsConfig;
	
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	public FileResult uploadFile(MultipartFile file){
		FileResult fileResult = new FileResult();
		try {
			byte[] bytes = file.getBytes();
			String originalFileName = file.getOriginalFilename();
			String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
			String fileName = file.getName();
			long fileSize = file.getSize();
			
			System.out.format("文件上传文件属性[originalFileName:{%s},fileName:{%s},fileSize:{%s},extension:{%s}, bytes.lengt:{%s}]",originalFileName,fileName,fileSize,extension,bytes.length);
			
			String url =  fastDFSClientWrapper.uploadFile(bytes, fileSize, extension);
			String resultUrl = fastdfsConfig.getOuturl() + url;
			System.out.format("文件地址：{%s}",resultUrl);
			
			fileResult.setOriginalFilename(originalFileName);
			fileResult.setFileUri(url);
			return fileResult;
		} catch (IOException e) {
			System.err.format("fastdfs上传文件失败，{%s}",e);
		}
		return null;
	}
	
	/**
	 * 下载文件
	 *
	 * @param fileUrl 文件URL
	 * @return 文件字节
	 * @throws IOException
	 */
	public byte[] downloadFile(String fileUrl) throws IOException {
		byte[] bytes = fastDFSClientWrapper.downloadFile(fileUrl);
		return bytes;
	}
	
	/**
	 * 删除文件
	 *
	 * @param fileUrl 文件URL
	 * @return 文件字节
	 * @throws IOException
	 */
	public  void deleteFile(String fileUrl) throws IOException {
		fastDFSClientWrapper.deleteFile(fileUrl);
	}
}
